package com.ttloner3.connectionpool;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author TTLoner
 * @date 2021/6/25 16:47
 * @description
 * 使用c3p0数据库连接池重构utils
 */
public class JDBCUtils {
    //通过C3P0方式
    private static ComboPooledDataSource cpds = new ComboPooledDataSource("helloc3p0");
    public static Connection getConnection1() throws SQLException {
        //通过xml文件
        //设置初始时数据库连接池中的连接数
        Connection conn = cpds.getConnection();
        return conn;
    }
    // DBCP方式
    private static DataSource source;
    static{
        Properties properties = new Properties();
        source=null;
        InputStream inputStream = ClassLoader.getSystemClassLoader().getResourceAsStream("DBCP.properties");
        try {
            properties.load(inputStream);
            source = BasicDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //DBCP方式
    public Connection getConnection2() throws Exception {
        Connection conn = source.getConnection();
        return conn;
    }
    private static DataSource sourceDruid;
    static {
        Properties properties = new Properties();
        InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("druid.properties");
        try {
            properties.load(is);
            sourceDruid = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //德鲁伊方式
    public Connection getConnection3() throws Exception {
        Connection conn = sourceDruid.getConnection();
        return conn;
    }
}
